<?php

namespace App\Http\Controllers\Admin;

use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class LoginController extends Controller
{
    public function sign(Request $request)
    {
        $credentials = $request->only('name', 'password');
        if (!Auth::attempt($credentials)) {
            return self::response(null,-1,'账号密码有误~');
        }
        $user = Auth::user();
        //生成token
        $time       = Carbon::now()->addHours(1)->timestamp;
        $ip         = $request->ip();
        $api_token  = str_random(60);
        $token      = encrypt([
                        'admin'     => 'api',
                        'time'      => $time,
                        'ip'        => $ip,
                        'name'      => $credentials['name'],
                        'password'  => $credentials['password'],
                        'api_token' => $api_token,
                    ]);
        $user->api_token = $api_token;
        $user->save();
        return self::response(['token' => $token],200);
    }

    public function logout(Request $request)
    {
        $admin_id = session('admin_id',0);
        if (empty($admin_id)) {
            return self::response(null,-1,'账号密码有误~');
        }
        $api_token  = str_random(60);
        $flag       = User::where('id','=',$admin_id)->update([
                            'api_token' => $api_token,
                        ]);
        if (empty($flag)) {
            return self::response(null,-2,'系统繁忙，请稍后再试哦~');
        }
        return self::response(null,200);
    }

    public function modifyPassword(Request $request)
    {
        $password = $request->input('password');
        $admin_id = session('admin_id',0);
        if (empty($admin_id)) {
            return self::response(null,-1,'账号密码有误~');
        }
        if (empty($password)) {
            return self::response(null,-2,'请输入新密码~');
        }
        if (!preg_match('/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?!.*\s).{6,20}/',$password)) {
            return self::response(null,-3,'密码长度为6到20位，必须包含有大写字母、小写字母、数字~');
        }
        $api_token  = str_random(60);
        $flag       = User::where('id','=',$admin_id)->update([
                            'password'  => Hash::make($password),
                            'api_token' => $api_token,
                        ]);
        if (empty($flag)) {
            return self::response(null,-4,'系统繁忙，请稍后再试哦~');
        }
        return self::response(null,200);
    }
}
